
$(function(){
    updateDepList();
    $('.content-title').on('click',function(){
        toggleDown(this);
    })

    // 查看指定员工信息
    $(document).on('click','.icon-gengduo',function(){
        loading();
        var thisId = $(this).children('input').val()
        $.ajax({
            url: path+"json/staff.json",//'/epi/staff/staffs/'+thisId,//path+"json/staff.json",
            // data: {
            //     id:thisId
            // },
            type: "GET",
            dataType: 'json',
            success: function(data) {
                loadingHide();
                var myTemplate = Handlebars.compile($("#staff-info-template").html());
                // console.log(myTemplate(data))
                $('.staff-info-div').html(myTemplate(data));
            },
            error: function() {
                setAlert('系统繁忙，请刷新重试');
            }
        });
        fadeModal('.information-modal');
    })

    // 删除员工
    $(document).on('click','.icon-lajitong',function(){
        var thisId = $(this).children('input').val();
        console.log(thisId);
        
        setConfirm('是否确定删除此员工',function(){
            loading();
            $.ajax({
                url: "/hhprojmgn/staff/"+$('.dep-id-input').val()+"/"+thisId,
                // data: {
                //     id:$('.dep-id-input').val()
                // },
                data: {
                    _method: 'DELECT'
                },
                // type: "DELECT",
                dataType: 'json',
                success: function(data) {
                    loadingHide();
                    var status = data.STATUS;
                    if (status == 500) {
                        setAlert('非法操作！');
                    } else if (status == 400) {
                        setAlert('删除员工失败！');
                    } else if (status == 200) {
                        $('tr').removeClass('selected');
                        $(this).parents('tr').first().addClass('selected');
                        $('.selected').remove();
                        setAlert('删除员工成功');
                    } else {
                        setAlert('系统繁忙，请刷新重试');
                    }
                },
                error: function() {
                    setAlert('系统繁忙，请刷新重试');
                }
            });
            
        })
    })

    // 修改部门信息模态框（内容页）
    $('.edit-btn').on('click',function(e){
        // 填充表单
        $('.form-control .dep-name').val($('.dep-info-name').html()),//部门名称
        $('.dep-type').val($('.dep-info-type').html()),//部门类别
        $('.dep-num').val($('.dep-info-num').html()),//部门编号
        $('.dep-date').val($('.dep-info-date').html()),//创建日期
        $('.dep-fax').val($('.dep-info-fax').html()),//传真
        $('.dep-phone').val($('.dep-info-phone').html()),//电话
        $('.area-name').val($('.area-info-name').html()),//区域名称
        $('.area-site').val($('.dep-info-site').html());//区域地址
        $('.dep-btn').attr('class','btn dep-btn edit-dep-btn');
        fadeModal('.edit-modal');
    })

    //部门人员信息
    $('.add-btn').on('click',function(){
        viewStaff(1);
        fadeModal('.add-modal');
    })

    // 修改部门
    $(document).on('click','.edit-dep-btn',function(){
        loading();
        // console.log(validateDep());
        if(validateDep() != undefined){
            $.ajax({
                url: "/hhprojmgn/department/",
                data: JSON.stringify({
//                     _method: "PUT",
                    departmentName: validateDep().depName,
                    departmentId:validateDep().depNum,
                    departmentType:validateDep().depType,
                    departmentAddress:validateDep().areaSite,
                    departmentPhone:validateDep().depPhone,
                    departmentFax:validateDep().depFax,
                    departmentAreaName:validateDep().areaName
                }),
                type: "PUT",
                dataType: 'json',
                contentType : "application/json",
                success: function(data) {
                    loadingHide();
                    var status = data.STATUS;
                    if (status == 500) {
                        setAlert('非法操作！');
                    } else if (status == 400) {
                        setAlert('修改失败！');
                    } else if (status == 200) {
                        var thisId = $('.dep-id-input').val();
                        updateDepList(thisId);
                        // fillDep('修改成功',
                        // validateDep().depName,
                        // validateDep().depType,
                        // validateDep().depNum,
                        // validateDep().depFax,
                        // validateDep().depPhone,
                        // validateDep().areaName,
                        // validateDep().areaSite);
                    } else {
                        setAlert('系统繁忙，请刷新重试');
                    }
                },
                error: function() {
                    setAlert('系统繁忙，请刷新重试');
                }
            });
            
        }
    });

    $('.dep-cancel-btn').on('click',function(){
        $('.edit-modal,.mask').fadeOut();
    });

    $('.dep-date').fdatepicker();

    $(document).on('click','.btn-info',function(){
        $('.information-modal,.mask').fadeOut();
    });

    $(document).on('mousedown','.dep-li',function(e){
        var depId = $(this).children('dep-li-id').val();
        var depPreId = $(this).children('dep-li-pre-id').val();
        $('.dep-id-input').val(depId);
        $('.dep-pre-id-input').val(depPreId);
        //屏蔽右键菜单
        document.oncontextmenu=function(){
            return false;
        }

        if(e.which == 3){

            $('.dep-li').removeClass('selected');
            $(this).addClass('selected');
            $('.right-menu').css({
                'left':mousePos(e).x,
                'top':mousePos(e).y
            })
            $('.right-menu').fadeIn();
        }

        return false;
    })

    $(document).click(function(){
        $('.right-menu').hide()
    })

    // 创建部门、创建子部门模态框
    $('.creat-dep,.creat-child-dep').click(function(){
        // 清空表单
        $('.form-control .dep-name').val(''),//部门名称
        $('.dep-type').val(''),//部门类别
        $('.dep-num').val(''),//部门编号
        // depDate = $('.dep-date').val(),//创建日期
        $('.dep-fax').val(''),//传真
        $('.dep-phone').val(''),//电话
        $('.area-name').val(''),//区域名称
        $('.area-site').val('');//区域地址
        // 改变按钮class
        $('.dep-btn').attr('class','btn dep-btn creat-dep-btn')
        fadeModal('.edit-modal');
    })

    // 创建部门、创建子部门
    $(document).on('click','.creat-dep-btn',function(){
        loading();
        // console.log(validateDep());
        if(validateDep() != undefined){
            $.ajax({
                url: "/hhprojmgn/department/",
                data: {
                    department_name: validateDep().depName,
                    department_id:validateDep().depNum,
                    department_Type:validateDep().depType,
                    department_address:validateDep().areaSite,
                    department_phone:validateDep().depPhone,
                    department_fax:validateDep().depFax,
                    department_area_name:validateDep().areaName
                },
                type: "POST",
                dataType: 'json',
                success: function(data) {
                    loadingHide();
                    var status = data.STATUS;
                    if (status == 500) {
                        setAlert('非法操作！');
                    } else if (status == 400) {
                        setAlert('部门创建失败失败！');
                    } else if (status == 200) {
                        var thisId = $('.dep-id-input').val();
                        updateDepList(thisId);
                        setAlert('部门创建成功');
                    } else {
                        setAlert('系统繁忙，请刷新重试');
                    }
                },
                error: function() {
                    setAlert('系统繁忙，请刷新重试');
                }
            });
            
        }
    });

    // 修改右键菜单模态框（右键菜单）
    $('.edit-dep').click(function(){
        loading();
        $.ajax({
            url: '/hhprojmgn/department/departments/'+$('.dep-id-input').val(),//path+"json/dep-information.json",
/*=======
            url: path+"json/dep-information.json",//'/epi/department/departments/'+$('.dep-id-input').val(),//path+"json/dep-information.json",
>>>>>>> develop*/
            // data: {
            //     id:$('.dep-id-input').val()
            // },
            type: "GET",
            dataType: 'json',
            success: function(data) {
                loadingHide();
                $('.form-control .dep-name').val(data.Name),//部门名称
                $('.dep-type').val(),//部门类别
                $('.dep-num').val(data.Id),//部门编号
                // $('.dep-date').val(data.CreateTime),//创建日期
                $('.dep-fax').val(data.Fax),//传真
                $('.dep-phone').val(data.Phone),//电话
                $('.area-name').val(data.AreaName),//区域名称
                $('.area-site').val(data.Address);//区域地址
                $('.dep-btn').attr('class','btn dep-btn edit-dep-btn');
                fadeModal('.edit-modal');
            },
            error: function() {
                setAlert('系统繁忙，请刷新重试');
            }
        });
        
    })

    // 删除部门
    $('.delete-dep,.delete-dep-btn').click(function(){
        setConfirm('确认删除此部门？',function(){
            loading();
            $.ajax({
                url: "/hhprojmgn/department/"+$('.dep-id-input').val(),
                /*data: {
                     _method: "DELETE"
                    // id:$('.dep-id-input').val()
                },*/
                type: "DELETE",
                dataType: 'json',
                success: function(data) {
                    loadingHide();
                    var status = data.STATUS;
                    if (status == 500) {
                        setAlert('非法操作！');
                    } else if (status == 400) {
                        setAlert('删除部门失败！');
                    } else if (status == 200) {
                        setAlert('部门删除成功');
                        updateDepList();
                    } else {
                        setAlert('系统繁忙，请刷新重试');
                    }
                },
                error: function() {
                    setAlert('系统繁忙，请刷新重试');
                }
            });
            
        })
    })

    //部门搜索
    $('.dep-search-btn').click(function(){
        var searchContent = $('.dep-search-input').val();
        for(var i=0;i<$('.dep-li').length;i++){
            console.log($('.dep-li').eq(i).text())
            if($('.dep-li').eq(i).text() == searchContent){
                $('.dep-li').eq(i).click();
            }           
        }
    })

    //点击部门列表
    $('.dep-list-div').on('click','.dep-li',function(){
        content = "";
        depObj = [];
        var id = $(this).children('.dep-li-id').val();
        updateDepList(id);
        $('.dep-id-input').val(id);
    })

    //点击
    $('#content').on('click','#breadcrumb .tip-bottom',function(){
        content = "";
        depObj = [];
        var id = $(this).children('input').val();
        updateDepList(id);
        
    })
    
    //上一页
    $('.staff-prev').on('click',function(){        
        if($('.page-num')[0].value > 1){
            $('.page-num')[0].value--;
            viewStaff($('.page-num')[0].value);
        }else{
            setAlert('已至第1页');
        }
    })

    // 下一页
    $('.staff-next').on('click',function(){
        $('.page-num')[0].value++;               
        viewStaff($('.page-num')[0].value);
        
    })
    


    
})

var content = "";
/**
 * [creatDeplist 创建部门列表]
 * @param  {[Object]} data [部门数据]
 * @return {[String]} content [DOM结构]
 */
function creatDeplist(data){
    // console.log(data.length)
    content += "<ul>";
    for(var i =0;i<data.length;i++){   
        if(!data[i].hasOwnProperty("children")){
            content += '<li class="dep-li">'+
                '<span class="dep-name">'+data[i].departmentName+'</span>'+
                '<input type="hidden" value="'+data[i].departmentId+'" class="dep-li-id">'+
                '<input type="hidden" value="'+data[i].departmentParentid+'" class="dep-li-pre-id">'+
                '</li>';
        }else{
            content += '<li class="dep-li">'+
                '<i class="iconfont icon-xiala"></i>'+
                '<span class="dep-name">'+data[i].departmentName+'</span>'+
                '<input type="hidden" value="'+data[i].departmentId+'" class="dep-li-id">'+
                '<input type="hidden" value="'+data[i].departmentParentid+'" class="dep-li-pre-id">'+
                '</li>';
            // var treeData = transData(data[i].chindren,"departmentId","departmentParentid","children");
            creatDeplist(data[i].children);
        }
    }
    content += "</ul>";
    return content;
}

/**
 * [updateDepList 更新部门列表]
 * @param  {[type]} id [所显示的部门id]
 */
function updateDepList(id){
    loading();
    $.ajax({
        //----------------------------------------------------------
        //url: path+"../hhprojmgn/assets/json/dep.json",//'/epi/department/departments/',//
        url:"/hhprojmgn/department/departments",
/*=======
        url: path+"json/dep.json",//'/epi/department/departments/',//path+"json/dep.json",
>>>>>>> develop*/
        type: "GET",
        dataType: 'json',
        success: function(data) {
            loadingHide();
            // console.log(data)
            // 
/*<<<<<<< HEAD
            creatDeplist(data); 
            //面包屑导航,默认显示第一个部门
             if(id == undefined){
                 var thisData = data[0];
                 while(thisData.sub != ""){
                     thisData = thisData.sub[0];
                 }
                 setBread(thisData._id);
                 viewDepInfor(thisData._id);
                 viewStaffInfor(thisData._id);
                
                
             }else{
                 setBread(id);
                 viewDepInfor(id);
                 viewStaffInfor(id);
             }                
=======*/
            var treeData = transData(data,"departmentId","departmentParentid","children");
            // creatDeplist(treeData);
            $('.dep-list').html(creatDeplist(treeData));
            // // 面包屑导航,默认显示第一个部门
            // console.log(id);
            if(id == undefined){
                var thisData = treeData[0];
                while(thisData.hasOwnProperty("children")){
                    thisData = thisData.children[0];
                }
                setBread(thisData.departmentId);
                viewDepInfor(thisData.departmentId);
                viewStaffInfor(thisData.departmentId);               
            }else{
                setBread(id);
                viewDepInfor(id);
                viewStaffInfor(id);
            }                
        },
        error: function() {
            setAlert('系统繁忙，请刷新重试1');
        }
    });
}

/**
 * [validateDep 部门操作验证]
 * @return {[Object]} [部门信息]
 */
function validateDep(){
    var depName = $('.form-control .dep-name').val(),//部门名称
        depType = $('.dep-type').val(),//部门类别
        depNum = $('.dep-num').val(),//部门编号
        // depDate = $('.dep-date').val(),//创建日期
        depFax = $('.dep-fax').val(),//传真
        depPhone = $('.dep-phone').val(),//电话
        areaName = $('.area-name').val(),//区域名称
        areaSite = $('.area-site').val();//区域地址
        if(depName == ''){
            setAlert('请填写部门名称');
        }else if(depType == ''){
            setAlert('请输入部门类别');
        }else if(depPhone == ''){
            setAlert('请输入电话号码');
        }else if(areaSite == ''){
            setAlert('请输入区域所在地');
        }else{
            return {
                depName:depName,
                depType:depType,
                depNum:depNum,
                depFax:depFax,
                depPhone:depPhone,
                areaName:areaName,
                areaSite:areaSite
            }
        }
}

/**
 * [fillDep 填充信息面板]
 * @param  {[String]} string   [提示文字]
 * @param  {[String]} depName  [部门名称]
 * @param  {[String]} depType  [部门类别]
 * @param  {[String]} depNum   [部门编号]
 * @param  {[String]} depFax   [部门传真]
 * @param  {[String]} depPhone [部门电话]
 * @param  {[String]} areaName [区域名称]
 * @param  {[String]} areaSite [区域地址]
 */
function fillDep(string,depName,depType,depNum,depFax,depPhone,areaName,areaSite){
    setAlert(string);
    $('.dep-info-name').html(depName);
    $('.dep-info-type').html(depType);
    $('.dep-info-num').html(depNum);
    // $('.dep-info-date').html(depDate);
    $('.dep-info-fax').html(depFax);
    $('.dep-info-phone').html(depPhone);
    $('.area-info-name').html(areaName);
    $('.dep-info-site').html(areaSite);
    $('.edit-modal').fadeOut();
}

/**
 * [mousePos 获取浏览器坐标]
 * @param  {[type]} e [description]
 * @return {[type]}   [x,y坐标]
 */
function mousePos(e){ 
  var x,y; 
  var e = e||window.event; 
  return { 
    x:e.clientX+document.body.scrollLeft + document.documentElement.scrollLeft, 
    y:e.clientY+document.body.scrollTop + document.documentElement.scrollTop 
  }; 
}; 

/**
 * [setBread 面包屑导航]
 * @param {[Object]} tipBottom [指定部门id]
 */
var depObj = [];
function setBread(id){
    // console.log(id)
    var idList = $('.dep-li-id');
    var breadcrumb = '';
    // console.log(idList.length)
    for(var i=0;i<idList.length;i++){
        // console.log(id);

        var idListVal = parseInt(idList.eq(i).val());
        // console.log(idListVal)
        if(id == idListVal){
            // console.log('-------------------------------')
            var depName = $('.dep-name').eq(i).text();
            console.log(depName)
            var preId = $('.dep-li-pre-id').eq(i).val();
            // console.log(depName)
            depObj.push({
                id:id,
                preId:preId,
                name:depName
            })
            if(preId != ""){
                setBread(preId);
                // console.log(preId)   
            }else{
                console.log(depObj)
                return depObj;
            }
        }
    }
    if(depObj != ''){
        for(var j=depObj.length-1;j>=0;j--){
            breadcrumb += '<a href="#" title="'+depObj[j].name+'" class="tip-bottom">'+
                            '<i class="iconfont icon-home"></i>'+
                            depObj[j].name+
                            '<input type="hidden" value="'+depObj[j].id+'">'+
                          '</a>';
        }
        console.log(breadcrumb)
        $('#breadcrumb').html(breadcrumb);
    }
}

/**
 * [viewDepInfor 查询指定部门信息]
 * @param  {[type]} id [指定部门id]
 */
function viewDepInfor(id){
    loading();
    $.ajax({
        url: '/hhprojmgn/department/departments/'+id,//path+"json/dep-information.json",
/*=======
        url: path+"json/dep-information.json",//'/epi/department/departments/'+id,//path+"json/dep-information.json",
>>>>>>> develop*/
        // data: {
        //     id:id
        // },
        type: "GET",
        dataType: 'json',
        success: function(data) {
            loadingHide();
            var myTemplate = Handlebars.compile($("#dep-info-template").html());
            $('.dep-information').html(myTemplate(data));
        },
        error: function() {
            setAlert('系统繁忙，请刷新重试');
        }
    });
}

/**
 * [viewStaffInfor 查询指定部门的员工信息]
 * @param  {[type]} id [指定部门id]
 */
function viewStaffInfor(id){
    loading();
    $.ajax({
/*<<<<<<< HEAD
        url: '/hhprojmgn/staff/staffs/'+id,///path+"json/link-staff.json",
=======*/
        url: path+"json/staff.json",//'/epi/staff/staffs/'+id,///path+"json/link-staff.json",

        // data: {
        //     id:id
        // },
        type: "GET",
        dataType: 'json',
        success: function(data) {
            loadingHide();
            var myTemplate = Handlebars.compile($("#staff-template").html());
            console.log(myTemplate(data))
            $('.staff-body').html(myTemplate(data));
        },
        error: function() {
            setAlert('系统繁忙，请刷新重试');
        }
    });
}

/**
 * [transData json格式转树状结构]
 * @param  {[json]} a           [json数据]
 * @param  {[String]} idStr       [id名称]
 * @param  {[String]} pidStr      [父id名称]
 * @param  {[String]} chindrenStr [子节点名称]
 * @return {[Array]}             [转化后的格式]
 */
function transData(a, idStr, pidStr, chindrenStr){    
    var r = [], hash = {}, id = idStr, pid = pidStr, children = chindrenStr, i = 0, j = 0, len = a.length;    
    for(; i < len; i++){    
        hash[a[i][id]] = a[i];    
    }    
    for(; j < len; j++){    
        var aVal = a[j], hashVP = hash[aVal[pid]];    
        if(hashVP){    
            !hashVP[children] && (hashVP[children] = []);    
            hashVP[children].push(aVal);    
        }else{    
            r.push(aVal);    
        }    
    }    
    return r;    
}

function viewStaff(pageNum, records) {
    if (records == undefined) {
        records = 10;
    }
    loading();
    $.ajax({
        url: path+"json/staff.json",//"/epi/staff/staffs/" +pageNum+"/"+records ,
        type: "GET",
        dataType: 'json',
        success: function(data) {
            loadingHide();
            if(data.length!=0){
                var myTemplate = Handlebars.compile($("#add-staff-template").html());
                console.log(data);
                // console.log(myTemplate(data));
                $('.add-staff-body').html(myTemplate(data));
            }else{
                setAlert('无更多数据');
                $('.page-num')[0].value--;           
            }
            
        },
        error: function() {
            setAlert('系统繁忙，请刷新重试');
        }
    });
}

